package com.apes.fico.masterdata.gl.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.fico.masterdata.gl.model.AccountingGroup;
import com.apes.fico.masterdata.gl.respository.AccountingGroupRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName AccountingGroupService
 * @Description TODO
 * @Author pengyb
 * @Date 2018/12/24 16:59
 * @Version 1.0
 **/
@Service("accountingGroupService")
public class AccountingGroupService extends DomainService {
    @Autowired
    private AccountingGroupRepository accountingGroupRepository;

    /**
     * 保存
     *
     * @param request
     * @return
     */
    public AccountingGroup save(SimpleRequest request) {
        AccountingGroup accountingGroup = request.getO(AccountingGroup.class);
        accountingGroup.setCreateDate(new Date());
        return accountingGroupRepository.saveAndFlush(accountingGroup);
    }

    /**
     * 修改
     * @param request
     * @return
     */
    public AccountingGroup update(SimpleRequest request){
        checkData(request);
        AccountingGroup accountingGroup=request.getO(AccountingGroup.class);
        accountingGroup.setUpdateDate(new Date());
        return accountingGroupRepository.saveAndFlush(accountingGroup);
    }

    /**
     * 删除
     * @param request
     * @return
     */
    public String delete (SimpleRequest request){
        checkData(request);
        AccountingGroup accountingGroup=request.getO(AccountingGroup.class);
        accountingGroupRepository.delete(accountingGroup.getId());
        return  "删除成功";
    }

    /**
     * 检查
     * @param request
     */
    public void checkData(SimpleRequest request){
        AccountingGroup accountingGroup=accountingGroupRepository.findOne((String)request.get("id"));
        if (accountingGroup==null) throw  new RuntimeException("科目组"+accountingGroup.getId()+"不存在");
        if (accountingGroup.getVersion()!=(int)request.get("version")) throw  new RuntimeException("科目组"+accountingGroup.getId()+"已更新或已删除");
    }

    /**
     * 下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<AccountingGroup> find(SimpleRequest request){
        return  accountingGroupRepository.find(request.get("key"),PageRequest.of(request.get("page"),request.get("size")));
    }
}
